#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
环境检查脚本 - 验证Frida环境是否就绪
"""

import sys
import subprocess
import io

# Fix encoding for Windows console
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')

print("\n" + "="*80)
print("🔍 Frida环境检查")
print("="*80 + "\n")

checks_passed = 0
checks_total = 0

def check(name, command, success_text, failure_text, critical=True):
    """执行检查"""
    global checks_passed, checks_total
    checks_total += 1
    
    print(f"[{checks_total}] 检查 {name}...")
    
    try:
        result = subprocess.run(
            command,
            shell=True,
            capture_output=True,
            text=True,
            timeout=5
        )
        
        if result.returncode == 0:
            print(f"    ✓ {success_text}")
            if result.stdout.strip():
                for line in result.stdout.strip().split('\n')[:3]:
                    print(f"      {line}")
            checks_passed += 1
            return True
        else:
            print(f"    ✗ {failure_text}")
            if result.stderr.strip():
                print(f"      错误: {result.stderr.strip()[:100]}")
            return False
            
    except subprocess.TimeoutExpired:
        print(f"    ✗ 超时")
        return False
    except Exception as e:
        print(f"    ✗ 异常: {e}")
        return False

# ============================================================================
# 1. Python版本
# ============================================================================
python_ok = check(
    "Python版本",
    "python --version",
    "Python已安装",
    "Python未安装或版本过低"
)

# ============================================================================
# 2. Frida
# ============================================================================
frida_ok = check(
    "Frida",
    "frida --version",
    "Frida已安装",
    "Frida未安装"
)

if not frida_ok:
    print("\n      安装方法:")
    print("        pip install frida frida-tools")

# ============================================================================
# 3. ADB
# ============================================================================
adb_ok = check(
    "ADB",
    "adb version",
    "ADB已安装",
    "ADB未安装"
)

if not adb_ok:
    print("\n      安装方法:")
    print("        Windows: 下载 Android SDK Platform-Tools")
    print("        https://developer.android.com/studio/releases/platform-tools")

# ============================================================================
# 4. ADB设备连接
# ============================================================================
if adb_ok:
    device_ok = check(
        "ADB设备",
        "adb devices",
        "设备已连接",
        "未找到设备"
    )
    
    if not device_ok:
        print("\n      解决方法:")
        print("        1. 确保手机通过USB连接")
        print("        2. 手机开启USB调试")
        print("        3. 手机允许USB调试授权")
else:
    device_ok = False
    checks_total += 1

# ============================================================================
# 5. Frida-server
# ============================================================================
if device_ok:
    print(f"\n[{checks_total + 1}] 检查 Frida-server...")
    checks_total += 1
    
    try:
        result = subprocess.run(
            'adb shell "ps | grep frida-server"',
            shell=True,
            capture_output=True,
            text=True,
            timeout=5
        )
        
        if "frida-server" in result.stdout:
            print("    ✓ Frida-server正在运行")
            checks_passed += 1
            frida_server_ok = True
        else:
            print("    ✗ Frida-server未运行")
            print("\n      启动方法:")
            print('        adb shell "su -c \'/data/local/tmp/frida-server &\'"')
            frida_server_ok = False
    except Exception as e:
        print(f"    ✗ 无法检查: {e}")
        frida_server_ok = False
else:
    frida_server_ok = False
    checks_total += 1

# ============================================================================
# 6. 检查必需文件
# ============================================================================
import os

print(f"\n[{checks_total + 1}] 检查必需文件...")
checks_total += 1

required_files = [
    "verify_rsa_key.js",
    "verify_ep_encryption.py"
]

missing_files = []
for f in required_files:
    if not os.path.exists(f):
        missing_files.append(f)

if not missing_files:
    print("    ✓ 所有必需文件存在")
    checks_passed += 1
else:
    print("    ✗ 缺少文件:")
    for f in missing_files:
        print(f"      - {f}")

# ============================================================================
# 7. Frida连接测试
# ============================================================================
if frida_ok and device_ok and frida_server_ok:
    print(f"\n[{checks_total + 1}] 测试Frida连接...")
    checks_total += 1
    
    try:
        import frida
        device = frida.get_usb_device(timeout=5)
        print(f"    ✓ 成功连接到设备: {device}")
        checks_passed += 1
    except Exception as e:
        print(f"    ✗ Frida连接失败: {e}")
        print("\n      可能的原因:")
        print("        1. frida-server版本与frida不匹配")
        print("        2. frida-server需要root权限")
        print("        3. SELinux阻止了连接")

# ============================================================================
# 总结
# ============================================================================
print("\n" + "="*80)
print("📊 检查结果")
print("="*80 + "\n")

print(f"通过: {checks_passed}/{checks_total}")

if checks_passed == checks_total:
    print("\n🎉 恭喜！环境已就绪，可以开始验证了！")
    print("\n下一步:")
    print("  python verify_ep_encryption.py")
else:
    print("\n⚠️  存在问题，请根据上面的提示解决")
    
    # 关键问题
    critical_issues = []
    
    if not python_ok:
        critical_issues.append("Python未安装")
    if not frida_ok:
        critical_issues.append("Frida未安装")
    if not adb_ok:
        critical_issues.append("ADB未安装")
    if not device_ok:
        critical_issues.append("设备未连接")
    if not frida_server_ok:
        critical_issues.append("Frida-server未运行")
    
    if critical_issues:
        print("\n🔴 关键问题:")
        for issue in critical_issues:
            print(f"  - {issue}")
        
        print("\n建议:")
        if not frida_ok:
            print("  1. 安装Frida: pip install frida frida-tools")
        if not adb_ok:
            print("  2. 安装ADB: 下载Android SDK Platform-Tools")
        if not device_ok:
            print("  3. 连接设备并开启USB调试")
        if not frida_server_ok:
            print("  4. 启动frida-server:")
            print('     adb push frida-server /data/local/tmp/')
            print('     adb shell "chmod 755 /data/local/tmp/frida-server"')
            print('     adb shell "su -c \'/data/local/tmp/frida-server &\'"')

print("\n" + "="*80 + "\n")

